package cn.com.youjile.init;

import cn.com.youjile.client.GeneralClient;
import cn.com.youjile.config.InitConfig;
import cn.com.youjile.server.GeneralServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.concurrent.CountDownLatch;

/**
 * @Author youjile
 * @CreateDate 2021/3/12
 * @Describe 启动的时候初始化
 */
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(ApplicationRunnerImpl.class);

    @Override
    public void run(ApplicationArguments args) {

        try {
            /**
             * 启动各个服务器
             */
            CountDownLatch latch = new CountDownLatch(1);                      //使用CountDownLatch，是为了各个服务按顺序启动
            if(InitConfig.serverClientFlag == 0) {
                new GeneralServer(InitConfig.heartBeatSencord, InitConfig.serverPort, latch).start();          //服务端启动
                latch.countDown();
            } else if(InitConfig.serverClientFlag == 1) {
                new Thread(new GeneralClient(InitConfig.host, InitConfig.clientPort)).start();        //客户端启动
                latch.countDown();
            }
        } catch (Exception e) {
            logger.error("初始化netty客户端异常！");
            e.printStackTrace();
        }
    }
}
